package com.dragonsen.log.logtrans

import com.android.build.api.transform.QualifiedContent
import com.android.build.api.transform.Transform
import com.android.build.api.transform.TransformException
import com.android.build.api.transform.TransformInvocation
import com.android.build.gradle.internal.pipeline.TransformManager
import com.dragonsen.baseplugin.BaseTransform
import com.dragonsen.baseplugin.ClassUtils
import com.dragonsen.baseplugin.TransformCallBack
import com.dragonsen.log.helper.LogClassNodeHelper
import com.google.common.collect.ImmutableSet
import java.io.IOException

abstract class LogTransform : Transform()  {

    /**
     * 执行这个 Transform 的 task 时，会以这个名字为基础生成 task 名称
     * */
    override fun getName(): String {
        return "LogTransform"
    }

    override fun getScopes(): MutableSet<in QualifiedContent.Scope> {
        return ImmutableSet.of(
                QualifiedContent.Scope.PROJECT
        )
    }

    override fun getInputTypes(): Set<QualifiedContent.ContentType>? {
        return TransformManager.CONTENT_CLASS
    }



    override fun isIncremental(): Boolean {
        return true
    }

    @Throws(TransformException::class, InterruptedException::class, IOException::class)
    override fun transform(transformInvocation: TransformInvocation) {
        val injectHelper = LogClassNodeHelper() //node节点方式
        //visitor方式
//        val injectHelper = LogAsmHelper()
        val baseTransform = BaseTransform(transformInvocation, object : TransformCallBack {
            override fun process(className: String, classBytes: ByteArray?): ByteArray? {
                if (ClassUtils.checkClassName(className)) {
                    try {
                        return classBytes?.let { injectHelper.modifyClass(it) }
                    } catch (e: IOException) {
                        e.printStackTrace()
                    }
                }
                return null
            }
        })
        baseTransform.startTransform()
    }

    override fun isCacheable(): Boolean {
        return true
    }
}